//
//  MYGAddSurgicalViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/24.
//

import UIKit
import BRPickerView
import AVFAudio
import AVFoundation
class MYGAddSurgicalViewController: MYGBaseController,AVAudioPlayerDelegate{
    var recorder:AVAudioRecorder? //录音器
    var player:AVPlayer!
    var recorderSeetingsDic:[String : Any]? //录音器设置参数数组
    var volumeTimer:Timer! //定时器线程，循环监测录音的音量大小
    var countTimer:Timer! //计时器

    var aacPath:String? //录音存储路径
    var infoModel:MYGSurgicalDetailModel = MYGSurgicalDetailModel()
    var voiceInputIndex:Int = 1
    var isStartTime:Bool = true
    var scan = false
    var count = 1
    var recodeAlert:MYGRecordVoiceAlert?
    var detailId = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "手术记录"
        initUI()
        initAvAudio()
        if scan {
            getDetailData()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(audioPlayCompletion), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

    }
       
    
    func getDetailData() {
        MYGLoading.show()
        MYGNetwork<MYGSurgicalApi, MYGSurgicalDetailModel>.request(target: .getSurgicalDetail(id: "\(detailId)")) {[weak self] item in
            self?.infoModel = item
            self?.bindData()
            MYGLoading.hide()
         
        } failed: {_, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func bindData() {
        addBtn.isHidden = true
        resultView.contentTf.text = infoModel.name
        resultView.isUserInteractionEnabled = false
        timeView.starTf.text = infoModel.start_at
        timeView.isUserInteractionEnabled = false
        timeView.endTf.text = infoModel.end_at
        huanzheView.contentTf.text = infoModel.patient_name
        huanzheView.isUserInteractionEnabled = false
        
        beforView.contentTf.text = infoModel.value.before_operation.text
        afterView.contentTf.text = infoModel.value.after_operation.text
        stepView.contentTf.text = infoModel.value.operation_steps.text
        otherView.contentTf.text = infoModel.value.other.text
        beforView.scan = scan
        afterView.scan = scan
        stepView.scan = scan
        otherView.scan = scan
        if infoModel.value.before_operation.voice.count > 0 {
            beforView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
        }
        if infoModel.value.after_operation.voice.count > 0 {
            afterView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
        }
        if infoModel.value.operation_steps.voice.count > 0 {
            stepView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
        }
        if infoModel.value.other.voice.count > 0 {
            otherView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
        }
    }
    
    @objc private func inviteAction(){
        MYGLoading.show()
        MYGNetwork<MYGSurgicalApi, MYGEmptyModel>.request(target: .addSurgicla(params: [
            "patient_id":infoModel.patient.id,
            "name":infoModel.name,
            "start_at":infoModel.start_at,
            "end_at":infoModel.end_at,
            "patient_name":infoModel.patient.name,
            "value":[
                "before_operation":["voice":infoModel.value.before_operation.voice,"media_id":"1","text":beforView.contentTf.text ?? ""],
                "after_operation":["voice":infoModel.value.after_operation.voice,"media_id":"1","text":afterView.contentTf.text ?? ""],
                "operation_steps":["voice":infoModel.value.operation_steps.voice,"media_id":"1","text":stepView.contentTf.text ?? ""],
                "other":["voice":infoModel.value.other.voice,"media_id":"1","text":otherView.contentTf.text ?? ""]]])) {[weak self] item in
                    MYGLoading.hide()
                    MMYGHUD.showToast(text: "添加成功")
                    NotificationCenter.default.post(name: Notification.Name("MYGSurgicalHistoryViewController_getDatasource"), object: nil)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                        self?.navigationController?.popViewController()
                    })
        } failed: { _, error in
            MYGLoading.hide()
        }
    }
    private func initAvAudio(){
        //初始化录音器
        let session:AVAudioSession = AVAudioSession.sharedInstance()
        
        //设置录音类型
        try! session.setCategory(AVAudioSession.Category.playAndRecord)
        //设置支持后台
        try! session.setActive(true)
        //获取Document目录
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                         .userDomainMask, true)[0]
        //组合录音文件路径
        aacPath = docDir + "/play.aac"
        //初始化字典并添加设置参数
        recorderSeetingsDic =
        [
            AVFormatIDKey: NSNumber(value: kAudioFormatMPEG4AAC),
            AVNumberOfChannelsKey: 2, //录音的声道数，立体声为双声道
            AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,
            AVEncoderBitRateKey : 320000,
            AVSampleRateKey : 44100.0 //录音器每秒采集的录音样本数
        ]
    }
    @objc func audioPlayCompletion() {
        // 播放完成后的操作
        print("播放完成")
        beforView.voiveplayBtn.isSelected = false
        afterView.voiveplayBtn.isSelected = false
        stepView.voiveplayBtn.isSelected = false
        otherView.voiveplayBtn.isSelected = false
    }
    func downAction() {
        //初始化录音器
        recorder = try! AVAudioRecorder(url: URL(string: aacPath!)!,
                                        settings: recorderSeetingsDic!)
        if recorder != nil {
            //开启仪表计数功能
            recorder!.isMeteringEnabled = true
            //准备录音
            recorder!.prepareToRecord()
            //开始录音
            recorder!.record()
            //启动定时器，定时更新录音音量
            volumeTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self,
                                               selector: #selector(levelTimer),
                                               userInfo: nil, repeats: true)
            countTimer = Timer.scheduledTimer(timeInterval: 1, target: self,
                                              selector: #selector(startCount),
                                              userInfo: nil, repeats: true)
        }
    }
    
    @objc func startCount() {
        self.recodeAlert?.timeLB.text = "\(count)S"
        count = count + 1
    }
    //松开按钮，结束录音
    func upAction(_ isSave:Bool = true) {
        //停止录音
        recorder?.stop()
        //录音器释放
        recorder = nil
       
        //暂停定时器
        volumeTimer.invalidate()
        volumeTimer = nil
        
        //暂停定时器
        count = 1
        countTimer.invalidate()
        countTimer = nil
        //            volumLab.text = "0"
        if isSave == false{return}
        let fileURL = NSURL(fileURLWithPath: aacPath!)
        do {
            // 尝试将文件内容转换为Data
            let fileData = try Data(contentsOf: fileURL as URL)
            // 使用fileData
            MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: nil, data: fileData, fileName: "\(Int(Date().timeIntervalSince1970)).mp3", type: "audio/*")) { _ in
                
            } stringBlock: {[self] text in
                print("text=\(text)")
                switch voiceInputIndex {
                case 1:
                    infoModel.value.before_operation.voice = text
                    break
                case 2:
                    infoModel.value.after_operation.voice = text
                    break
                case 3:
                    infoModel.value.operation_steps.voice = text
                    break
                case 4:
                    infoModel.value.other.voice = text
                    break
                default:
                    break
                }
            } failed: { _, err in
                
            }
            print(fileData)
        } catch {
            // 处理错误
            print("Error converting file to Data: \(error)")
        }
        
    }
    //播放录制的声音
    @objc func playAction(btn:UIButton) {
        beforView.voiveplayBtn.isSelected = false
        afterView.voiveplayBtn.isSelected = false
        stepView.voiveplayBtn.isSelected = false
        otherView.voiveplayBtn.isSelected = false
        var urlString = ""
        switch btn.tag {
        case 1:
            beforView.voiveplayBtn.isSelected = true
            urlString = infoModel.value.before_operation.voice
            break
        case 2:
            afterView.voiveplayBtn.isSelected = true
            urlString = infoModel.value.after_operation.voice
            break
        case 3:
            stepView.voiveplayBtn.isSelected = true
            urlString = infoModel.value.operation_steps.voice
            break
        case 4:
            otherView.voiveplayBtn.isSelected = true
            urlString = infoModel.value.other.voice
            break
        default:
            break
        }
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                         .userDomainMask, true)[0]
       
        //播放
        
        player = AVPlayer(url: URL(string: urlString)!)
//        player = try! AVAudioPlayer(contentsOf: URL(string: aacPath!)!)
//        player?.delegate = self
        if player == nil {
            print("播放失败")
        }else{
            player.play()
        }
    }
    func showRecordVoiceAlert() {
        self.popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = Bundle.main.loadNibNamed("MYGRecordVoiceAlert", owner: nil)?.first as! MYGRecordVoiceAlert
            actionSheet.tapSaveCompletion = {[weak self] in
                guard let `self` = self else {return}
                self.popup.dismissPopup()
                self.endRecord()
            }
            self.recodeAlert = actionSheet
            actionSheet.dismissBlock = {[weak self] in
                guard let `self` = self else {return}
                self.popup.dismissPopup()
                self.upAction(false)
            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: bottomSafeheight + 265)
            return actionSheet
        }
    }
    //定时检测录音音量
    @objc func levelTimer(){
        recorder!.updateMeters() // 刷新音量数据
        let averageV:Float = recorder!.averagePower(forChannel: 0) //获取音量的平均值
        let maxV:Float = recorder!.peakPower(forChannel: 0) //获取音量最大值
        let lowPassResult:Double = pow(Double(10), Double(0.05*maxV))
        //        volumLab.text = "\(lowPassResult)"
    }
    @objc func longPressAction(_ sender: UITapGestureRecognizer) {
        voiceInputIndex = sender.view?.tag ?? 1
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                         .userDomainMask, true)[0]
        //组合录音文件路径
        aacPath = docDir + "/play\(sender.view?.tag ?? 1).aac"
        
        showRecordVoiceAlert()
        downAction()
    }
    
    func endRecord() {
        upAction()
        switch voiceInputIndex {
        case 1:
            beforView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
            break
        case 2:
            afterView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
            break
        case 3:
            stepView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
            break
        case 4:
            otherView.snp.updateConstraints { make in
                make.height.equalTo(152)
            }
            break
        default:
            break
        }
    }
    
    private func initUI(){
        view.backgroundColor = .white
        view.addSubview(scView)
        scView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(50)
        }
        scView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(screenWidth)
        }
        
        containerView.addSubview(resultView)
        containerView.addSubview(timeView)
        containerView.addSubview(huanzheView)
        containerView.addSubview(typeView)
        containerView.addSubview(typeLabel)
        containerView.addSubview(beforView)
        beforView.voiveRecordBtn.tag = 1
        beforView.voiveplayBtn.tag = 1
        containerView.addSubview(afterView)
        afterView.voiveRecordBtn.tag = 2
        afterView.voiveplayBtn.tag = 2
        containerView.addSubview(stepView)
        stepView.voiveRecordBtn.tag = 3
        stepView.voiveplayBtn.tag = 3
        containerView.addSubview(otherView)
        otherView.voiveRecordBtn.tag = 4
        otherView.voiveplayBtn.tag = 4
        
        
        
        let longPressGesture = UITapGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        beforView.voiveRecordBtn.addGestureRecognizer(longPressGesture)
        
        let longPressGesture2 = UITapGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        afterView.voiveRecordBtn.addGestureRecognizer(longPressGesture2)
        
        let longPressGesture3 = UITapGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        stepView.voiveRecordBtn.addGestureRecognizer(longPressGesture3)
        
        let longPressGesture4 = UITapGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        otherView.voiveRecordBtn.addGestureRecognizer(longPressGesture4)
        
        //        beforView.deleteBtn.addTarget(self, action: #selector(playAction(btn:)), for: .touchUpInside)
        //        afterView.deleteBtn.addTarget(self, action: #selector(playAction(btn:)), for: .touchUpInside)
        //        stepView.deleteBtn.addTarget(self, action: #selector(playAction(btn:)), for: .touchUpInside)
        //        otherView.deleteBtn.addTarget(self, action: #selector(playAction(btn:)), for: .touchUpInside)
        
        resultView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(55)
        }
        timeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.width.equalTo(screenWidth)
            make.top.equalTo(resultView.snp.bottom)
            make.height.equalTo(55)
        }
        huanzheView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(timeView.snp.bottom)
            make.height.equalTo(55)
        }
        typeView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(17.5)
            make.top.equalTo(huanzheView.snp.bottom).offset(20.5)
            make.size.equalTo(CGSize(width: 3, height: 15))
        }
        typeLabel.snp.makeConstraints { make in
            make.left.equalTo(typeView.snp.right).offset(5)
            make.centerY.equalTo(typeView)
            make.height.equalTo(25)
        }
        beforView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(82)
            make.top.equalTo(typeLabel.snp.bottom).offset(10)
        }
        afterView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(82)
            make.top.equalTo(beforView.snp.bottom)
        }
        stepView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(82)
            make.top.equalTo(afterView.snp.bottom)
        }
        otherView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(82)
            make.top.equalTo(stepView.snp.bottom)
            make.bottom.equalToSuperview().offset(-70)
        }
        
        UIViewController.keyWindow?.addSubview(dateBackView)
        dateBackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(50)
            make.bottom.equalToSuperview()
        }
        addBtn.addCAGradientLayerColor(colors: [RGBA(r: 73, g: 117, b: 236, a: 1).cgColor,RGBA(r: 151, g: 179, b: 255, a: 1).cgColor], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 1, y: 0))
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    private lazy var addBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("添加手术记录", for: .normal)
        vi.titleLabel?.font = .medium(17)
        vi.setTitleColor(.white, for: .normal)
        vi.addTarget(self, action: #selector(inviteAction), for: .touchUpInside)
        return vi
    }()
    private lazy var dateBackView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(51, 51, 51,0.3)
        cont.isHidden = true
        cont.addSubview(datePicker)
        datePicker.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(SCALEWIDTH(200))
        }
        let vi = UIView()
        vi.backgroundColor = .white
        cont.addSubview(vi)
        vi.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(datePicker.snp.top)
            make.height.equalTo(SCALEWIDTH(40))
        }
        let btn = UIButton()
        btn.setTitle("确定", for: .normal)
        btn.titleLabel?.font = .regular(15)
        btn.setTitleColor(.blue, for: .normal)
        btn.addTarget(self, action: #selector(doneDateSelect), for: .touchUpInside)
        vi.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-SCALEWIDTH(20))
            make.bottom.top.equalToSuperview()
            make.width.equalTo(SCALEWIDTH(40))
        }
        
        let cancel = UIButton()
        cancel.setTitle("取消", for: .normal)
        cancel.titleLabel?.font = .regular(15)
        cancel.setTitleColor(.blue, for: .normal)
        cancel.addTarget(self, action: #selector(tapCancel), for: .touchUpInside)
        vi.addSubview(cancel)
        cancel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(20))
            make.bottom.top.equalToSuperview()
            make.width.equalTo(SCALEWIDTH(40))
        }
        return cont
    }()
    
    @objc func tapCancel() {
        dateBackView.isHidden = true
    }
    //确定日期选择
    @objc func doneDateSelect() {
        dateBackView.isHidden = true
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let currentDateString = formatter.string(from: datePicker.date)
        if isStartTime == true{
            timeView.starTf.text = currentDateString
            self.infoModel.start_at = currentDateString
            
        }else{
            timeView.endTf.text = currentDateString
            self.infoModel.end_at = currentDateString
            
        }
        dateBackView.isHidden = true
    }
    //MARK: lazy
    private lazy var datePicker:UIDatePicker = {
        let cont = UIDatePicker()
        cont.datePickerMode = .dateAndTime
        if #available(iOS 13.4, *) {
            cont.preferredDatePickerStyle = .wheels
        } else {
            // Fallback on earlier versions
        }
        cont.minimumDate = Date()
        cont.locale = Locale(identifier: "zh_CN")
        cont.backgroundColor = .white
        return cont
    }()
    
    private lazy var scView:UIScrollView = {
        let cont = UIScrollView()
        return cont
    }()
    private lazy var containerView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .white
        return cont
    }()
    private lazy var resultView:singleSelectView = {
        let cont = singleSelectView()
        cont.titleLab.text = "*诊断"
        cont.contentTf.placeholder = "请选择诊断结果"
        cont.selectBlock = {[self] value in
            self.infoModel.name = value
        }
        return cont
    }()
    private lazy var timeView:timeSelectView = {
        let cont = timeSelectView()
        cont.titleLab.text = "*手术时间"
        cont.startTimeBlock = {[self] value in
            self.isStartTime = true
            self.dateBackView.isHidden = false
            UIViewController.keyWindow?.bringSubviewToFront(self.dateBackView)
        }
        cont.endTimeBlock = { value in
            self.isStartTime = false
            self.dateBackView.isHidden = false
            UIViewController.keyWindow?.bringSubviewToFront(self.dateBackView)
        }
        return cont
    }()
    private lazy var huanzheView:singleSelectView = {
        let cont = singleSelectView()
        cont.titleLab.text = "*选择患者"
        cont.contentTf.placeholder = "请选择患者"
        cont.huanzheBlock = {[self] value in
            self.infoModel.patient = value
        }
        return cont
    }()
    private lazy var typeView:UIImageView = {
        let cont = UIImageView()
        cont.image = UIImage(named: "MYG_home_type")
        return cont
    }()
    private lazy var typeLabel:UILabel = {
        let cont = UILabel()
        cont.textColor = RGBA(r: 51, g: 51, b: 51, a: 1)
        cont.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        cont.text = "手术经过"
        return cont
    }()
    private lazy var beforView:voiceInputView = {
        let cont = voiceInputView()
        cont.titleLab.text = "术前诊断:"
        cont.playBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
        }
        cont.stopBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
            beforView.voiveplayBtn.isSelected = false
            afterView.voiveplayBtn.isSelected = false
            stepView.voiveplayBtn.isSelected = false
            otherView.voiveplayBtn.isSelected = false
            player?.pause()
        }
        cont.deleteBlock = {[self] btn in
            infoModel.value.before_operation.voice = ""
            cont.snp.updateConstraints { make in
                make.height.equalTo(82)
            }
        }
        return cont
    }()
    private lazy var afterView:voiceInputView = {
        let cont = voiceInputView()
        cont.titleLab.text = "术后诊断:"
        cont.playBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
        }
        cont.stopBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
            beforView.voiveplayBtn.isSelected = false
            afterView.voiveplayBtn.isSelected = false
            stepView.voiveplayBtn.isSelected = false
            otherView.voiveplayBtn.isSelected = false
            player?.pause()
        }
        cont.deleteBlock = {[self] btn in
            infoModel.value.after_operation.voice = ""
            cont.snp.updateConstraints { make in
                make.height.equalTo(82)
            }
        }
        return cont
    }()
    private lazy var stepView:voiceInputView = {
        let cont = voiceInputView()
        cont.titleLab.text = "手术步骤:"
        cont.playBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
        }
        cont.stopBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
            beforView.voiveplayBtn.isSelected = false
            afterView.voiveplayBtn.isSelected = false
            stepView.voiveplayBtn.isSelected = false
            otherView.voiveplayBtn.isSelected = false
            player?.pause()
        }
        cont.deleteBlock = {[self] btn in
            infoModel.value.operation_steps.voice = ""
            cont.snp.updateConstraints { make in
                make.height.equalTo(82)
            }
        }
        return cont
    }()
    private lazy var otherView:voiceInputView = {
        let cont = voiceInputView()
        cont.titleLab.text = "其他:"
        cont.playBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
        }
        cont.stopBlock = {[self] btn in
            self.playAction(btn: cont.voiveplayBtn)
            beforView.voiveplayBtn.isSelected = false
            afterView.voiveplayBtn.isSelected = false
            stepView.voiveplayBtn.isSelected = false
            otherView.voiveplayBtn.isSelected = false
            player?.pause()
        }
        cont.deleteBlock = {[self] btn in
            infoModel.value.other.voice = ""
            cont.snp.updateConstraints { make in
                make.height.equalTo(82)
            }
        }
        return cont
    }()
    
}
class singleSelectView:UIView{
    var selectBlock:((String)->())?
    var huanzheBlock:((MYGPatientModel)->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectAction))
        self.addGestureRecognizer(tap)
        
    }
    @objc func selectAction(){
        switch contentTf.placeholder {
        case "请选择诊断结果":
            BRStringPickerView.showPicker(withTitle: "请选择诊断结果", dataSourceArr: ["主动脉瓣","二尖瓣","三尖瓣","肺动脉瓣","自定义"], select: 0) {[self] item in
                self.selectBlock?(item?.value ?? "")
                contentTf.text = item?.value ?? ""
            }
            break
        case "请选择患者":
            showHuanzeAlert()
            break
        default:
            break
        }
    }
    
    func showHuanzeAlert() {
        self.rootResponsder().popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = MYGSurgicalManSelectView()
            actionSheet.selectBlock = {[self] value in
                let mode:MYGPatientModel = value
                huanzheBlock?(mode)
                contentTf.text = mode.name
            }
            actionSheet.dismissBlock = {
                self.rootResponsder().popup.dismissPopup()
            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight)
            return actionSheet
        }
    }
    
  
    func initUI(){
        addSubviews([titleLab,contentTf,moreImage,lineView])
        titleLab.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(26)
            make.height.equalTo(22.5)
        }
        moreImage.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-26)
            make.size.equalTo(CGSize(width: 6, height: 11))
            make.centerY.equalToSuperview()
        }
        contentTf.snp.makeConstraints { make in
            make.right.equalTo(moreImage.snp.left).offset(-6)
            make.centerY.equalToSuperview()
            make.height.equalTo(22.5)
        }
        lineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(25)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
//        UIViewController.keyWindow?.addSubview(huanzheSelect)
//        huanzheSelect.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var titleLab = {
        let cont = UILabel()
        cont.font = .regular(16)
        return cont
    }()
    lazy var contentTf = {
        let cont = UITextField()
        cont.font = .regular(16)
        cont.textAlignment = .right
        cont.isUserInteractionEnabled = false
        return cont
    }()
    private lazy var moreImage: UIImageView = {
        let cont = UIImageView()
        cont.image = UIImage(named: "MYG_home_moreJ")
        return cont
    }()
    private lazy var lineView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(238, 238, 238, 1)
        return cont
    }()
    
}
class timeSelectView:UIView{
    var startTimeBlock:((String)->())?
    var endTimeBlock:((String)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    @objc func selectStartTimeAction(){
        startTimeBlock!("")
    }
    @objc func selectEndTimeAction(){
        endTimeBlock!("")
    }
    func initUI(){
        addSubviews([titleLab,endTf,centerView,starTf,lineView])
        titleLab.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(26)
            make.height.equalTo(22.5)
        }
        let tfWidth = (screenWidth - 130)/2
        endTf.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-5)
            make.height.equalTo(22.5)
            make.width.equalTo(tfWidth)
            make.centerY.equalToSuperview()
        }

        centerView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(endTf.snp.left).offset(-3)
            make.size.equalTo(CGSize(width: 14, height: 1))
        }
        starTf.snp.makeConstraints { make in
            make.right.equalTo(centerView.snp.left).offset(-3)
            make.height.equalTo(22.5)
            make.width.equalTo(tfWidth)
            make.centerY.equalToSuperview()
        }
        lineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(25)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var titleLab = {
        let cont = UILabel()
        cont.font = .regular(16)
        return cont
    }()
    lazy var starTf:UITextField = {
        let cont = UITextField()
        cont.font = .regular(12)
        //        cont.isEnabled = false
        cont.placeholder = "开始时间"
        cont.textAlignment = .center
        cont.adjustsFontSizeToFitWidth = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectStartTimeAction))
        cont.addGestureRecognizer(tap)
        return cont
    }()
    lazy var endTf:UITextField = {
        let cont = UITextField()
        cont.font = .regular(12)
        //       cont.isEnabled = false
        cont.placeholder = "结束时间"
        cont.textAlignment = .center
        cont.adjustsFontSizeToFitWidth = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectEndTimeAction))
        cont.addGestureRecognizer(tap)
        return cont
    }()
    private lazy var centerView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(0, 0, 0, 1)
        return cont
    }()
    private lazy var lineView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(238, 238, 238, 1)
        return cont
    }()
}
class voiceInputView:UIView{
    var playBlock:((_ btn:UIButton)->())?
    var stopBlock:((_ btn:UIButton)->())?
    var deleteBlock:((_ btn:UIButton)->())?
    
    var scan:Bool = false {
        didSet {
            self.deleteBtn.isHidden = scan
            self.voiveRecordBtn.isUserInteractionEnabled = !scan
            self.contentTf.isUserInteractionEnabled = !scan
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    @objc func playAction(btn:UIButton){
        btn.isSelected = !btn.isSelected
        if btn.isSelected == true{
            if playBlock != nil{
                playBlock!(btn)
            }
        }else{
            if stopBlock != nil{
                stopBlock!(btn)
            }
        }
    }
    @objc func deleteAction(btn:UIButton){
        if deleteBlock != nil{
            deleteBlock!(btn)
        }
    }
    private func initUI(){
        self.layer.masksToBounds = true
        addSubview(titleLab)
        titleLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(26)
            make.top.equalToSuperview().offset(16.5)
            make.height.equalTo(22.5)
        }
        addSubview(voiveRecordBtn)
        voiveRecordBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-27)
            make.top.equalToSuperview().offset(14)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        addSubview(contentTf)
        contentTf.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(26)
            make.right.equalToSuperview().offset(-26)
            make.top.equalTo(titleLab.snp.bottom).offset(15)
            make.height.equalTo(20)
        }
        addSubview(voiceView)
        voiceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(26)
            make.top.equalTo(contentTf.snp.bottom).offset(10)
            make.size.equalTo(CGSizeMake(166, 35))
        }
        voiceView.addSubview(voiveplayBtn)
        voiveplayBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(9)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 20, height: 20))
        }
        voiceView.addSubview(voiceImageView)
        voiceImageView.snp.makeConstraints { make in
            make.left.equalTo(voiveplayBtn.snp.right).offset(7)
            make.centerY.equalToSuperview()
            make.height.equalTo(25)
            make.right.equalToSuperview().offset(-11.5)
        }
        addSubview(timeLabel)
        timeLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(26)
            make.top.equalTo(voiceView.snp.bottom).offset(7.5)
            make.height.equalTo(16.5)
        }
        addSubview(deleteBtn)
        deleteBtn.snp.makeConstraints { make in
            make.left.equalTo(timeLabel.snp.right).offset(15)
            make.centerY.equalTo(timeLabel)
            make.height.equalTo(16.5)
        }
        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(25)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(1)
            //            make.top.equalTo(deleteBtn.snp.bottom).offset(12)
            make.bottom.equalToSuperview()
        }
    }
    lazy var titleLab:UILabel = {
        let cont = UILabel()
        cont.textColor = .rgba(51, 51, 51)
        cont.font = .medium(16)
        return cont
    }()
    lazy var contentTf:UITextField = {
        let cont = UITextField()
        cont.font = .regular(16)
        cont.placeholder = "请输入内容"
        return cont
    }()
    var voiveRecordBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "surgical_record"), for: .normal)
        return btn
    }()
    lazy var voiceView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(229, 251, 230, 1)
        cont.layer.masksToBounds = true
        cont.layer.cornerRadius = 17.5
        return cont
    }()
    lazy var voiveplayBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "surgical_paly"), for: .normal)
        btn.setImage(UIImage(named: "surgical_zanting"), for: .selected)
        btn.addTarget(self, action: #selector(playAction(btn:)), for: .touchUpInside)
        return btn
    }()
    lazy var voiceImageView:UIImageView = {
        let btn = UIImageView()
        btn.image = UIImage(named: "surgical_wave")
        return btn
    }()
    private lazy var timeLabel:UILabel = {
        let cont = UILabel()
        cont.textColor = .rgba(165, 165, 165, 1)
        cont.font = .regular(12)
        return cont
    }()
    lazy var deleteBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("删除", for: .normal)
        btn.titleLabel?.font = .regular(12)
        btn.setTitleColor(.rgba(100, 100, 100, 1), for: .normal)
        btn.addTarget(self, action: #selector(deleteAction(btn:)), for: .touchUpInside)
        return btn
    }()
    private lazy var lineView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(238, 238, 238, 1)
        return cont
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
